const db = uniCloud.database();
const videoDataCollection = db.collection('video_data');

console.log('categoryManage initializing...');

exports.main = async (event, context) => {
  const { action, label, value, oldValue } = event;

  console.log('categoryManage invoked:', { action, label, value });

  try {
    switch (action) {
      case 'get':
        // 获取分类列表
        const res = await videoDataCollection.where({ type: 'category' }).get();
        console.log('Categories fetched:', res.data.length);
        return {
          code: 0,
          data: res.data,
          msg: '获取分类列表成功'
        };

      case 'add':
        // 添加分类
        if (!label || !value) {
          return { code: -1, msg: '分类名称和值不能为空' };
        }
        const existing = await videoDataCollection.where({ type: 'category', value }).get();
        if (existing.data.length > 0) {
          return { code: -1, msg: '分类值已存在' };
        }
        await videoDataCollection.add({
          _id: `category_${value}`,
          type: 'category',
          label,
          value
        });
        console.log('Category added:', { label, value });
        return { code: 0, msg: '添加分类成功' };

      case 'update':
        // 更新分类
        if (!label || !value || !oldValue) {
          return { code: -1, msg: '分类名称、值和旧值不能为空' };
        }
        const existingUpdate = await videoDataCollection.where({ type: 'category', value }).get();
        if (existingUpdate.data.length > 0 && value !== oldValue) {
          return { code: -1, msg: '新分类值已存在' };
        }
        await videoDataCollection.where({ type: 'category', value: oldValue }).update({ label, value });
        await videoDataCollection.where({ type: 'video', category: oldValue }).update({ category: value, category_label: label });
        console.log('Category updated:', { oldValue, newValue: value, label });
        return { code: 0, msg: '更新分类成功' };

      case 'delete':
        // 删除分类
        if (!value) {
          return { code: -1, msg: '分类值不能为空' };
        }
        const videos = await videoDataCollection.where({ type: 'video', category: value }).get();
        if (videos.data.length > 0) {
          return { code: -1, msg: '该分类下存在视频，无法删除' };
        }
        await videoDataCollection.where({ type: 'category', value }).remove();
        console.log('Category deleted:', { value });
        return { code: 0, msg: '删除分类成功' };

      default:
        return { code: -1, msg: '无效的操作' };
    }
  } catch (e) {
    console.error(`分类操作失败 (${action}):`, e);
    return { code: -1, msg: `操作失败: ${e.message}` };
  }
};